

<template>
  <div class="subpage">
    <my-head title="修改密码">
      <van-icon name="revoke" class="hicon" @click="gotoback" />
    </my-head>
    <van-form ref="form" @submit="onSubmit" @failed="onFail">
      <van-field
        v-model="form.password"
        name="password"
        label="旧密码"
        placeholder="请输入旧密码"
        clearable
        type="password"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: reg.pwd,
            message: '请输入6-16的数字字母组合',
          },
          {
            validator: asynvCheckPass,
            message: '旧密码不正确',
          },
        ]"
      />
      <van-field
        v-model="form.newpassword"
        name="newpassword"
        label="新密码"
        placeholder="请输入新密码"
        clearable
        type="password"
        :rules="[
          { required: true, message: '请填写新密码' },
          {
            pattern: reg.pwd,
            message: '请输入6-16的数字字母组合',
          },
        ]"
        @blur="checkDBPass"
      />
      <van-field
        v-model="form.dbpassword"
        name="dbpassword"
        label="确认新密码"
        placeholder="请输入确认新密码"
        clearable
        type="password"
        :rules="[
          { required: true, message: '请确认密码' },
          {
            pattern: reg.pwd,
            message: '请输入6-16的数字字母组合',
          },
          {
            validator: checkNewPass,
            message: '两次密码不一致',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="danger" native-type="submit"
          >修改提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {},
    };
  },
  methods: {
    onFail() {
      this.showErrMsg("请输入有效的数据");
    },
    async onSubmit(value) {
      let res = await this.$ajax.changeuser(this.userInfo.id, {
        password: value.newpassword,
      });
      if (res) {
        this.$toast("密码修改成功,请重新登录");
        this.$router.push({ name: "login" });
        this.changeUserInfo(null);
      } else {
        this.showErrMsg("修改密码,请重新再试");
      }
    },
    async asynvCheckPass(val) {
      //  this.userInfo.password == val
      let res = await this.$ajax.findUser({
        username: this.userInfo.username,
      });
      return res[0].password == val;
    },
    checkNewPass(val) {
      if (this.reg.pwd.test(this.form.newpassword)) {
        return this.form.newpassword == val;
      }
    },
    checkDBPass() {
      if (
        this.reg.pwd.test(this.form.newpassword) &&
        this.reg.pwd.test(this.form.dbpassword)
      ) {
        this.$refs.form.validateField("dbpassword");
      }
    },
  },
};
</script>